﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NewAI.Game;

namespace NewAI.FSM.JsonAnalyzerFSM
{
    public class JsonAnalyzer : IBaseEntity
    {
        public List<ActionObj> actionObjs;
        public int roundID;
        public Thread timeThread;
        public State<JsonAnalyzer> currentState;

        public FSMMessage OneRoundMessage { private set; get; } = new FSMMessage();
        public FSMMessage LegStartMessage { private set; get; } = new FSMMessage();
        public FSMMessage LegEndMessage { private set; get; } = new FSMMessage();
        public FSMMessage ActionMessage { private set; get; } = new FSMMessage();

        public int ActionTimeOut { set; get; }
        public System.Threading.Timer timer;//超时计时器

        public JsonAnalyzer(int actionSendTimeOut = 400)
        {
            ActionTimeOut = actionSendTimeOut;
            if (ActionTimeOut <= 0)
                ActionTimeOut = 400;
            actionObjs = new List<ActionObj>();
            PubliceMessage.CloseAllMessage.OnEvent += OnCloseAll;
        }

        public void OnReceiveGameServerDataMessage(object sender, FSMEventEventArg args)
        {
            ChangeState(new JsonAnalyseState(args.Msg));
        }

        public void OnReceiveTankAIActionMessage(object sender, FSMEventEventArg args)
        {
            ChangeState(new BuildActionJsonState(args.Obj as ActionObj));
        }

        public void OnCloseAll(object sender, FSMEventEventArg args)
        {
            if (timeThread != null && timeThread.IsAlive)
                timeThread.Abort();
            if (currentState != null)
            {
                currentState.Exit(this);
                currentState = null;
            }
        }

        public void ChangeState(State<JsonAnalyzer> state)
        {
            if (currentState != null)
                currentState.Exit(this);
            currentState = state;
            currentState.Enter(this);
        }

        public void Update()
        {
            currentState.Execute(this);
        }

        public void StartTimeOurTimer()
        {
            CloseTimeOutTimer();
            timer = new System.Threading.Timer(new TimerCallback(TimeOut), null, ActionTimeOut, ActionTimeOut);
        }

        public void CloseTimeOutTimer()
        {
            if (timer != null)
            {
                timer.Dispose();
                timer = null;
            }
        }

        private void TimeOut(object obj)
        {
            CloseTimeOutTimer();
            ChangeState(new DirectSendActionState(roundID, actionObjs));
        }
    }
}
